package com.javatest.ajax.app2.bean;

import lombok.Data;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2018-09-03 下午4:34
 */
@Data
public class ShoppingCart {
    // 存放ShoppingCartItem的map，key：书名
    private Map<String, ShoppingCartItem> items;

    private String currentBook;

    public ShoppingCart() {
        this.items = new HashMap<>();
    }

    public void addToCart(String bookName, int price) {
        this.currentBook = bookName;
        if (items.containsKey(bookName)) {
            ShoppingCartItem item = items.get(bookName);
            item.setNumber(item.getNumber() + 1);
        } else {
            ShoppingCartItem item = new ShoppingCartItem();
            item.setNumber(1);
            item.setBookName(bookName);
            item.setPrice(price);

            items.put(bookName, item);
        }
    }

    public int getTotalBookNumber() {
        int total = 0;
        for (Map.Entry<String, ShoppingCartItem> entry : items.entrySet()) {
            total += entry.getValue().getNumber();
        }
        return total;
    }

    public int getTotalMoney() {
        int total = 0;
        for (ShoppingCartItem item : items.values()) {
            total += item.getPrice() * item.getNumber();
        }
        return total;
    }

}
